package com.zhongkai.service.impl;

import com.zhongkai.Bean.PageBean;
import com.zhongkai.app.service.PageQuerDao;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository("pageDao")
public class PageQuerDaoImpl extends HibernateDaoSupport implements PageQuerDao {

    @Resource
    public void setMySessionFactory(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }
    @Override
    public void pageQuery(PageBean pageBean) {
        int currentPage = pageBean.getCurrentPage();
        int pageSize = pageBean.getPageSize();
        DetachedCriteria detachedCriteria = pageBean.getDetachedCriteria();


        //查询total---总数据量
        detachedCriteria.setProjection(Projections.rowCount());//指定hibernate框架发出sql的形式----》select count(*) from bc_staff;
        List<Object> countList = (List<Object>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
        Long count =  Long.valueOf(countList.get(0).toString());
        pageBean.setTotal(count.intValue());


        //LogMF.log();
        //查询rows---当前页需要展示的数据集合
        detachedCriteria.setProjection(null);//指定hibernate框架发出sql的形式----》select * from bc_staff;
        int firstResult = (currentPage - 1) * pageSize;
        int maxResults = pageSize;
        List rows = this.getHibernateTemplate().findByCriteria(detachedCriteria, firstResult, maxResults);
        pageBean.setRows(rows);
    }

    @Override
    public Long pageMax(Object object) {

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(object.getClass());


        //查询total---总数据量
        detachedCriteria.setProjection(Projections.rowCount());//指定hibernate框架发出sql的形式----》select count(*) from bc_staff;
        List<Long> countList = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
        Long count = countList.get(0);

        return count;
    }

    @Override
    public List pageMax2(DetachedCriteria detachedCriteria) {
        List countList = (List) this.getHibernateTemplate().findByCriteria(detachedCriteria);

        return countList;
    }

    @Override
    public Long getCount(DetachedCriteria detachedCriteria) {

        List<Long> countList = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
        Long count = countList.get(0);

        return count;
    }
}
